package cn.micai.base.io;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import java.io.IOException;

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/8/23 10:48
 * @Description: 将Java对象序列化成XML格式，将XML反序列化还原为Java对象
 */
public class XmlSerializeDeserializeMain {

    /**
     * 将Java对象序列化成XML格式
     * @param employee
     * @return
     * @throws IOException
     */
    public static String serialize(Employee employee){
        // 将employee对象序列化为XML
        XStream xStream = new XStream(new DomDriver());
        // 设置employee类的别名
        xStream.alias("employee", Employee.class);
        String personXml = xStream.toXML(employee);
        return personXml;
    }

    /**
     * 将XML反序列化还原为Java对象
     * @param personXml
     * @return
     */
    public static Employee deserialize(String personXml) {
        // 将employee对象序列化为XML
        XStream xStream = new XStream(new DomDriver());
        xStream.alias("employee", Employee.class);
        Employee employee = (Employee) xStream.fromXML(personXml);
        return employee;
    }

    public static void main(String [] args) {

        Employee employee = new Employee();
        employee.setEmployeeId(1);
        employee.setEmployeeName("赵新国");
        employee.setDepartment("软件工程师");
        // 序列化
        String serialize = serialize(employee);
        System.out.println(serialize);
        // 反序列化
        Employee deserialize = deserialize(serialize);
        System.out.println(deserialize.toString());

    }

}
